<?php
/*
* Ebay Auth key
* Prepares the Ebay Auth Key for the Request
*
 * @category Ebay
 * @package Ebay_AuthKey
 * @author Luke Parry
 */
class Ebay_AuthKey
{
    //Declare a few constants
    const ACTIVE = 'Active';
    const EXPIRED = 'Expired';
    const INVALID = 'Invalid';
    const OTHER = 'Other';

	protected $_ebayAuthToken = null;
	protected $_request;
    protected $_xml;
    protected $_user;
    protected $_status = null;

	public function __construct($uid)
	{
        //Construct some helper classes
		$this->_request = new Ebay_HttpClient();
        //$this->_request->init(); //Prepare the request Object
        $this->_xml = new Ebay_XmlWriter();

        //Fetch the latest copy of the user directly from the database
        $Users = new Users();
        $this->_user = $Users->fetchRow($Users->select()->where('uid = ?', $uid));
        $data = unserialize($this->_user->data);
        $this->_ebayAuthToken = ( isset($data->ebayAuthToken) ) ? $data->ebayAuthToken : '';
	}

    public function getStatus()
    {
        return (is_null($_status)) ? false: $this->_status;
    }

	/**
	 * A non-validated method that just returns the raw token.
	 *
	 */
	public function getToken()
	{
		return $this->_ebayAuthToken;
	}

	//Calls GetTokenStatus
	public function getTokenStatus()
	{
		$callName = 'GetTokenStatus';

		$this->_xml->create();

		$this->_xml->push('RequesterCredentials')
                   ->push('eBayAuthToken', $this->_ebayAuthToken)->pop(2);

        $config = Zend_Registry::getInstance()->get('config')->ebay->api;

        $this->_request->setHeaders(array('X-EBAY-API-DEV-NAME' => $config->devName,
                                          'X-EBAY-API-CERT-NAME' => $config->certName,
                                          'X-EBAY-API-APP-NAME' => $config->appName));

		$response = $this->_request->call($callName, $this->_xml);
        $status = $response->TokenStatus->Status;

        switch($status)
        {
            case self::ACTIVE: $this->_status = self::ACTIVE; break;
            case self::EXPIRED: $this->_status = self::EXPIRED; break;
            case self::INACTIVE: $this->_status = self::INACTIVE; break;
            default: $this->_status = self::OTHER; break;
        }

		if($this->_status == self::ACTIVE)
		{
            return true;
    	}
		else //The Authcode has expired or has failed to validate with Ebay's Servers
		{
            //Delete the previously stored token in the database
            $data = unserialize($this->_user->data);
            unset($data->ebayAuthToken);
            $this->_user->data = serialize($data);
            $this->_user->save();
            return false;

            //TODO PUT THIS IN ANOTHER FUNCTION
            //Retrieve the new Auth Code
            $this->GetSessionID();
        }
	}

	public function getSessionID()
	{
		$callName = 'GetSessionID';
		$this->_xml->create(); //Destroy previous doc and start with blank doc

		$config = Zend_Registry::getInstance()->get('config')->ebay->api;

        //Include the runame that is later checked once the user has logged in
        $this->_xml->push('RuName', $config->runame)->pop()->end();

        //Set the headers to include the authorisation tokens


		$response = $this->_request->call($callName, $this->_xml);

		/*
	         * Check to ensure session ID matches 32 characters as stated in
	         * http://developer.ebay.com/devzone/xml/docs/reference/ebay/GetSessionID.html#Response.SessionID
	         */
		if(strlen($response->SessionID) == 32)
		{
			$session = new Zend_Session_Namespace('User'); // store in the user session for laters

			$session->SessionID = $response->SessionID;
		}
		else
		{
			throw new Ebay_Exception("The session Id recieved was malformed");

        }
	}
	public function fetchToken()
	{
		$callName = 'FetchToken';

		$session = new Zend_Session_Namespace('User'); // store in the user session for laters

		$this->_xml->create()->push('SessID', $session->SessionID)->pop()->end(); //Create the document and add the session Id

        $config = Zend_Registry::getInstance()->get('config')->ebay->api;

        $this->_request->setHeaders(array('X-EBAY-API-DEV-NAME' => $config->devName,
                                          'X-EBAY-API-CERT-NAME' => $config->certName,
                                          'X-EBAY-API-APP-NAME' => $config->appName));

		$response = $this->_request->call($callName, $this->_xml);

		if(isset($response->eBayAuthToken))
		{
            $data = unserialize($this->_user->data);
            $data->ebayAuthToken = $response->eBayAuthToken;

            $this->_user->data = serialize($data);
            $this->_user->save();

			return true;
		}
		else
		{
			throw new Ebay_Exception("The attempt to get the authentication token failed.");
		}
	}
}